package sanphone.com.runningschool.MyOrder;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import sanphone.com.runningschool.BaseActivity;
import sanphone.com.runningschool.ForceOffline;
import sanphone.com.runningschool.InterfaceLocation;
import sanphone.com.runningschool.JuShou.JuShouDetailActivity;
import sanphone.com.runningschool.R;
import sanphone.com.runningschool.RequestHttp.RequestHttp;

public class SendOrderActivity extends BaseActivity implements View.OnClickListener {

    private Toolbar toolbar;
    private TextView publisher_name;
    private TextView send_order_content;
    private TextView send_order_status;
    private Button finish_order;
    private String status,userId,behaviorId;
    private TextView txt2;
    private Intent intent;
    private SharedPreferences sprf;
    private ImageView delete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_order);
        sprf=getSharedPreferences("data",MODE_PRIVATE);
        userId=sprf.getString("schoolId",null);
        ForceOffline offline=new ForceOffline(userId,this);
        offline.check();
        initView();
    }
    private void initView() {
        toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        txt2=findViewById(R.id.txt2);
        publisher_name = findViewById(R.id.p_name);
        send_order_content = findViewById(R.id.send_order_content);
        send_order_status = findViewById(R.id.send_order_status);
        finish_order = findViewById(R.id.finish_order);
        delete=findViewById(R.id.send_order_delete);
        intent=getIntent();
        status = intent.getStringExtra("status");
        Log.e("SendOrderStatus",status );
        if (status.equals("CLOSE")) {
            txt2.setVisibility(View.VISIBLE);
            send_order_status.setText("已完成");
        }
        else if(status.equals("OPEN")){
            txt2.setVisibility(View.VISIBLE);
           send_order_status.setText("未接单");
        }  else{
            txt2.setVisibility(View.GONE);
            send_order_status.setVisibility(View.GONE);
            finish_order.setVisibility(View.VISIBLE);
            finish_order.setOnClickListener(this);

        }
        behaviorId= intent.getStringExtra("behaviorId");
        publisher_name.setText(intent.getStringExtra("nickName"));
        send_order_content.setText("物品名称：" + intent.getStringExtra("thingName") + "\n" + "物品重量：" + intent.getDoubleExtra("thingWeight",0.0)+"kg"
                + "\n起始时间：" + intent.getStringExtra("thingTime")
                + "\n送达时间：" + intent.getStringExtra("deliverTime") + "\n起始地址：" + intent.getStringExtra("thingPlace") +
                "\n送达地址：" + intent.getStringExtra("deliverPlace") + "\n酬劳：" + intent.getIntExtra("money",0)+"元"
                + "\n接单者：" + intent.getStringExtra("acceptName") + "\n联系方式："+ intent.getStringExtra("acceptPhone"));
        delete.setOnClickListener(this);


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                SendOrderActivity.this.finish();
                break;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.finish_order:
                Log.e("sendOrder", userId +behaviorId);
                Post(userId,behaviorId);
                break;
            case R.id.send_order_delete:
                AlertDialog.Builder builder=new AlertDialog.Builder(v.getContext());
                builder.setTitle("温馨提示");
                builder.setMessage("是否删除订单？");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteOrder();
                    }
                });
                builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.show();
                break;
        }
    }

    private void Post(final String userId, final String behaviorId) {
        ExecutorService executorService= Executors.newSingleThreadExecutor();
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                JSONObject json=new JSONObject();
                try {
                    json.put("schoolId",userId);
                    json.put("behaviorId",Integer.valueOf(behaviorId));
                    RequestHttp requestHttp=new RequestHttp(InterfaceLocation.getLocation()+"closeBehaviorStatus",SendOrderActivity.this);
                    String response=requestHttp.post(json);
                    //Log.e("sendOrder", response );
                    JSONObject responseJson=new JSONObject(response);
                    if(responseJson.getString("data").equals("操作成功")){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(SendOrderActivity.this,"操作成功",Toast.LENGTH_SHORT).show();
                                SendOrderActivity.this.finish();
                            }
                        });
                    }else{
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(SendOrderActivity.this,"操作失败，请重试",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        executorService.shutdown();
    }

    private void deleteOrder() {
        Log.e("userid behaviorId ",userId+" "+behaviorId );
        ExecutorService executorService=Executors.newSingleThreadExecutor();
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject json=new JSONObject();
                    json.put("schoolId",userId);
                    json.put("behaviorId",Integer.valueOf(behaviorId));
                    RequestHttp requestHttp=new RequestHttp(InterfaceLocation.getLocation()+"userDeleteBehavior",SendOrderActivity.this);
                    String response=requestHttp.post(json);
                    JSONObject responseJson=new JSONObject(response);
                    String data=responseJson.getString("data");
                    Log.e("deleteOrder ", data);
                    if(data.equals("删除成功")){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(SendOrderActivity.this,"订单删除成功！",Toast.LENGTH_SHORT).show();
                                SendOrderActivity.this.finish();
                            }
                        });

                    }else{
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(SendOrderActivity.this,"订单删除失败,请重试！",Toast.LENGTH_SHORT).show();
                            }
                        });

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        executorService.shutdown();
    }
}
